<?php
require_once SITE_ROOT_PATH.'/_lib/classes/class.supplier.php';
require_once SITE_ROOT_PATH.'/_lib/base/curl_multirequest.php';
require_once SITE_ROOT_PATH.'/_lib/classes/class.hotels.php';
require_once SITE_ROOT_PATH.'/_lib/classes/class.hotel_search.php';


class suppliers {
  
    protected $suppliers = array();
    protected $results   = array();
  
  public function __construct() {
    // load suppliers from configuration file
    $xo = simplexml_load_file(SUPPLIERS_CONFIG_FILE, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($xo) {
            foreach ($xo as $supplier) {
        $asupplier = new supplier($supplier);
        $this->suppliers[$asupplier->get_id()] = $asupplier;
      }
    }    
  }

    public function hotel_search($form_params) {       
        $search_queries = array();
// build search queries for all suppliers
        foreach ($this->suppliers as $supplier) {
            $search_queries[$supplier->get_id()] = $supplier->build_search_query($form_params);
        }               
        $results = $this->execute_search($search_queries);
         // process results
        // transform result XMLs to native XML result format
        $xp = new XsltProcessor();
        // create a DOM document and load the XML datat
        $xml_doc = new DomDocument;
        // create a DOM document and load the XSL stylesheet
        $xsl = new DomDocument;
        // native results storage
        $native = array();
        foreach ($results as $supplier=>$result) {
            $xsl->load($this->suppliers[$supplier]->get_xslt_path("search"));
            // import the XSL styelsheet into the XSLT process
            $xp->importStylesheet($xsl);      
            if (@$xml_doc->loadXML($result)) {
                $native[$supplier] = $xp->transformToXml($xml_doc);
            } else {
                // signal error
                $GLOBALS['note'] = array('type'=>'neg', 'message'=>'System error occured. Please do another search. If error repeats, please contact site\'s administration');
                $this->log_error($supplier, $search_queries[$supplier]."\n\n".$result);
                $native[$supplier] = "";
            }
        }
        
        // free objects
        $xsl = null;
        $xml_doc = null;
        $xp = null;
        $results = null;
        $results = array();
        $results["hotels"] = array();
        $results["rooms_count"] = intval($form_params['search_params']["no_rooms"]);
        $results["nights"] = intval($form_params['search_params']["nights"]);
        $results["arrival_date"] = $form_params['search_params']["arrival_date"];

        $results['destination_tree_id'] = $form_params['search_params']['destination_tree_id'];
    // process native XMLs, build associative arrays with data from them and merge all suppliers' hotels
        
    foreach($native as $supplier=>$xml) {
      $xo = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
      if($xo && isset($xo->session)) {
        $session_id = trim($xo->session->id);
        $currency = trim($xo->session->Currency);
        foreach($xo->session->Hotel as $value) {
          $hotel = (array)$value;
          $rooms = $hotel["Rooms"];
          unset($hotel["Rooms"]);
          $hotel["session_id"] = $session_id;
          $hotel["currency"] = $currency;
          $hotel["supplier_code"] = $supplier;
          
          if(isset($rooms->Room_1)) {
            $hotel["room_sets"][1]["adults"] = intval($rooms->Room_1->Passengers->Adults);
            $hotel["room_sets"][1]["children"] = intval($rooms->Room_1->Passengers->Children);
            foreach($rooms->Room_1->Room as $room) {
              $hotel["room_sets"][1]["rooms"][(string)$room->ID] = (array)$room;
            }
          }
          if(isset($rooms->Room_2)) {
            $hotel["room_sets"][2]["adults"] = intval($rooms->Room_2->Passengers->Adults);
            $hotel["room_sets"][2]["children"] = intval($rooms->Room_2->Passengers->Children);
            foreach($rooms->Room_2->Room as $room) {
              $hotel["room_sets"][2]["rooms"][(string)$room->ID] = (array)$room;
            }
          }
          if(isset($rooms->Room_3)) {
            $hotel["room_sets"][3]["adults"] = intval($rooms->Room_3->Passengers->Adults);
            $hotel["room_sets"][3]["children"] = intval($rooms->Room_3->Passengers->Children);
            foreach($rooms->Room_3->Room as $room) {
              $hotel["room_sets"][3]["rooms"][(string)$room->ID] = (array)$room;
            }
          }

          $hotel["facility"] = (string)$hotel["facility"];
                    
          // ???
          // $hotel["room_types"] = "room types";
          // $hotel["room_name"] = "room name";
          $results["hotels"][] = $hotel;
        }
      }
    }
   
    $results = $this->hotel_descriptions($results);

    return $results;
  }



    protected function hotel_descriptions($results){
        $search = new hotelSearch();
        if (FEATURE_HOTEL_MAPPING) {
            $results = $this->hotel_map($results); 
        } else {
            $results = $search->postprocess_results($results);
        }
        
        return $results;
    }
    
    

  public function hotel_map($data) {
    $hotels = array();
    $h = new hotels();
        foreach ($data["hotels"] as $hotel) {
    	$hotel_values = $h->lookup_hotel($hotel);
      // If found add to array
            if ($hotel_values) {
        $hotels[$hotel_values["extra"]["hotel_id"]] = $hotel_values;
            } else {
  	  // Else flag as not found
                if (FEATURE_HOTEL_FLAGGING) {
  	  	$h->flag_hotel_instance($hotel);
  	  }
    }
        }
    $data["hotels"] = $hotels;
    return $data;
  }

  public function set_results($results) {
    $this->results = $results;
  }

  public function hotel_list($page) {
    // TODO: implement pagination here
    return $this->results;
  }
  
  public function hotel_book($data) {
    $result = $this->suppliers[$data["supplier_code"]]->hotel_book($data);
    $result["supplier_code"] = $data["supplier_code"];
    return $result;
  }
  
public function cancel_booking($data) {
$result = $this->suppliers[$data["supplier_code"]]->cancel_booking($data);
$result["supplier_code"] = $data["supplier_code"];
return $result;
}

  public function get($id) {
    if(isset($this->suppliers[$id])) {
      return $this->suppliers[$id];
    }
    else return null;
  }
  
  protected function execute_search($queries) {
    // quick cache for 1 supplier "youtravel" case
    if(count($queries)==1 && isset($queries["you"])) {
      $hash = md5($queries["you"]);
      if(isset($_SESSION[$hash])) {
        $result = $_SESSION[$hash];
      }
      else {
        $result = curl_multirequest($queries);
        $_SESSION[$hash] = $result;
      }
      return $result;
    }
    else {
      $result = curl_multirequest($queries);
      return $result;
    }
  }
  
  
  

  
  protected function log_error($supplier, $message) {
   
    //file_put_contents("logs/errors/".$supplier."-".date("Ymd-His"), $message);
  }
  
   
   
  
  
  
}
